package com.hangim.pce.common.service.impl;

import com.hangim.pce.common.service.BaseAmqpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 核心队列服务，有关系统业务方便的通用封装在这个服务里面实现
 */
public abstract class BaseAmqpServiceImpl<T> implements BaseAmqpService {
    private final static Logger logger = LoggerFactory.getLogger(BaseAmqpServiceImpl.class);

    @Autowired
    protected AmqpTemplate amqpTemplate;

    @RabbitHandler
    public void handler(T t) {
        for (int i = 1; i <= 3; i++) {
            try {
                execute(t);
                break;
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                if (i == 3) {
                    throw new AmqpRejectAndDontRequeueException(e.getMessage()); //出现异常时，抛出这个异常告诉MQ不要重发
                } else {
                    try {
                        Thread.sleep(1000);                 //1000 毫秒，也就是1秒.
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
    }

    /**
     * 用于子类中实现具体的业务
     *
     * @param t 消息内容
     */
    public abstract void execute(T t);

    public AmqpTemplate getAmqpTemplate() {
        return amqpTemplate;
    }

    public void setAmqpTemplate(AmqpTemplate amqpTemplate) {
        this.amqpTemplate = amqpTemplate;
    }

    protected boolean isAmqpEnable() {
        return true;
    }
}
